<?php
/**
 * Created by PhpStorm.
 * User: zgh
 * Date: 2021-08-05
 * Time: 14:45
 */

namespace app\admin\service;

use app\admin\item\MessageLoader;
use app\admin\pipeline\ItemAdapter;
use app\common\model\MessageModel;
use app\common\model\UserModel;


class MessageService
{
    public static function getByID($id)
    {
        $adapter = new ItemAdapter(MessageModel::class);
        return $adapter->get($id)->getModel();
    }

    public static function getList($params)
    {
        $pagination = filter_pagination(@$params['page'], @$params['limit']);
        $where = [];
        $data = [];
        $loader = new MessageLoader();
        $where = $loader->addVal($params)
            ->addWhereSearch("title", "str", true)
            ->addWhereSearch("content", "str", true)
            ->addWhereSearch("is_deal", "int")
            ->addWhere(["status", "<>", -1])->setWhereAlias("m")->loadWhere();
        $query = MessageModel::alias("m")
            ->field("m.*,u.nickname  as user_name,u.mobile as user_mobile")
            ->leftJoin(UserModel::getMagicTableName() . " u", "m.user_id=u.id")
            ->where($where)->order(["m.id" => "desc"]);
        $data['total'] = $query->count();
        $data['dataList'] = [];
        if ($data['total']) {
            $datalist = $query->limit($pagination['start'], $pagination['limit'])->select()->toArray();
            $data['dataList'] = $loader->clear()->addVal($datalist)->loadItem();
        }
        return $data;
    }


    public static function save($params)
    {
        $adapter = new ItemAdapter(MessageModel::class);
        $res = $adapter->save($params);
        if ($res) {
            return $adapter->getId();
        } else {
            return false;
        }
    }


    public static function del($params)
    {
        $adapter = new ItemAdapter(MessageModel::class);
        return $adapter->whereUpdate([["id", "in", $params['id']]], ["status" => -1]);
    }

    public static function batchDeal($params)
    {
        $adapter = new ItemAdapter(MessageModel::class);
        return $adapter->whereUpdate([["id", "in", $params['id']]], ["is_deal" => 1]);
    }
}